package com.levi.producer;


import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 发送同步消息  收到发送结果之后再往下继续发送消息
 */

public class SyncProducer {
    public static void main(String[] args) throws Exception {
        /**
         * 1.创建生产者，指定生产者组
         * 2.指定nameserver地址
         * 3.启动producer
         * 4.创建消息，指定topic，tag，消息体
         * 5.发送消息
         * 6.关闭producer
         */
        //1.创建生产者，指定生产者组
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        //2.指定nameserver地址
        producer.setNamesrvAddr("124.220.27.193:9876");
//        producer.setSendMsgTimeout(1000000);
//        //消息发送失败时候，重试次数
//        producer.setRetryTimesWhenSendFailed(5);
        //3.启动producer
        producer.start();
        //4.创建消息，指定topic，tag，消息体
        for (int i = 1; i <= 20; i++) {
            Message message = new Message("base","tagA",("hello rocketmq"+i).getBytes(StandardCharsets.UTF_8));
            //5.发送消息,在5秒内没有发送成功就重试
            SendResult result = producer.send(message,10000);
            //消息id
            String msgId = result.getMsgId();
            //消息发送状态
            SendStatus sendStatus = result.getSendStatus();
            //消息的队列
            MessageQueue messageQueue = result.getMessageQueue();
            System.out.println("消息id: "+msgId+" 消息发送状态: "+sendStatus+" 消息队列: "+messageQueue);
            TimeUnit.SECONDS.sleep(1);
        }


        //6.关闭producer
        producer.shutdown();
    }

}
